//
//  NewsViewController.m
//  BSLCar
//
//  Created by dlios on 15/5/22.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "NewsViewController.h"
#import "XDKAirMenuController.h"

@interface NewsViewController ()

@property (nonatomic, retain) UIButton *button;

@end

@implementation NewsViewController

- (void)dealloc
{
    [_arrayData release];
    [_tmpStr release];
    [super dealloc];
}

- (void)barButtonAction:(UIBarButtonItem *)barButton {
    if ([[XDKAirMenuController sharedMenu] isMenuOpened]) {
        
        [[XDKAirMenuController sharedMenu] closeMenuAnimated];
    } else {
        [[XDKAirMenuController sharedMenu] openMenuAnimated];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"返回";
    self.navigationItem.backBarButtonItem = item;
    [item release];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(-5, 0, 25, 23);
    [button setImage:[UIImage imageNamed:@"iconfont-caidan.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(barButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] autorelease] initWithCustomView:button];
    
    //给页面设置头的字
    self.navigationItem.title = @"汽车新闻";

    //创建uitableview
    newsTable  = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    //签订协议
    newsTable.delegate = self;
    newsTable.dataSource = self;
    //添加tableview
    [self.view addSubview:newsTable];
    //创建分割线的特色
    newsTable.separatorColor = [UIColor grayColor];
    newsTable.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    //第三方
    
    [newsTable addHeaderWithTarget:self action:@selector(xiala)];
    [newsTable addFooterWithTarget:self action:@selector(shangla)];
    
    [newsTable headerBeginRefreshing];
    
    //请求 和里面包含的解析
    NSString *str = @"http://www.im4s.cn/trade/data/baidunews.xml";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
       //request.HTTPMethod = @"GET";
    NSError *error = nil;
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //创建解析类1
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    //设置代理
    parser.delegate = self;
    //开始解析
    [parser parse];
    
   // [btnReset release];
    [newsTable release];
    [parser release];
    
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.button.backgroundColor = [UIColor redColor];
    [self.button setImage:[UIImage imageNamed:@"iconfont-sh"] forState:UIControlStateNormal];
    self.button.frame = CGRectMake(self.view.bounds.size.width - 40, self.view.bounds.size.height - 110, 30, 30);
    //    [self.button setTitle:@"回到顶上" forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(topButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.button];
    self.button.hidden = YES;

}

- (void)topButton:(UIButton *)sender {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    [newsTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


#pragma －mark xml解析方法的代理
//1.代理方法1
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    //头节点
    //发现头节点
    if ([elementName isEqualToString:@"document"]) {
        //初始化数组
        self.arrayData = [NSMutableArray array];
    }
    else if ([elementName isEqualToString:@"item"]){
        NewsModel *model = [NewsModel getAllNewsModel];
        [self.arrayData addObject:model];
        
    }

}
//2.代理方法2
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //发现节点内容
    //记录节点内容
    self.tmpStr = string;
    
}
//3.代理方法3
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    //发现尾节点
    //取出newsmodel
    NewsModel *news = [self.arrayData lastObject];
    if ([elementName isEqualToString:@"title"]) {
        news.title = self.tmpStr;
    }
    else if ([elementName isEqualToString:@"text"]){
        news.text = self.tmpStr;
    }
    else if ([elementName isEqualToString:@"image"]){
        news.imgStr = self.tmpStr;
    }
    else if ([elementName isEqualToString:@"pubDate"]){
        news.dateTime = [self.tmpStr substringToIndex:10];
        
    }
    else if ([elementName isEqualToString:@"link"]){
//        NFirstViewController *first = [[NFirstViewController alloc] init];
        news.link = self.tmpStr;
        
    }
    
}
//4.代理方法4，解析成功
- (void)parserDidEndDocument:(NSXMLParser *)parser{
    //检验解析是否成功
}

 //签订协议方法，在里面填充内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell0";
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
    }
    
    if (indexPath.row == 20) {
        self.button.hidden = NO;
    }
    
    if (indexPath.row == 2) {
        self.button.hidden = YES;
    }

    
    //重点在cell里面添加内容，添加model里面的值
    NewsModel *news = [self.arrayData objectAtIndex:indexPath.row];
    cell.titleLabel.text = news.title;
    cell.txtLabel.text = news.text;
    cell.timeLabel.text = news.dateTime;
    cell.label.text = @"查看详情";
    //放图片用系统的方法
    NSURL *url = [NSURL URLWithString:news.imgStr];

    [cell.imgIcon sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Bei"]];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 165;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayData.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NFirstViewController *first = [[NFirstViewController alloc] init];
    //记得model一定从array里面取出来
    NewsModel *news = [self.arrayData objectAtIndex:indexPath.row];
    first.InterfaceId = news.link;

    [self.navigationController pushViewController:first animated:YES];
    //传值
}
-(void)xiala
{
    //结束，刷新
    [newsTable headerEndRefreshing];
}

-(void)shangla
{
    [newsTable footerEndRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
